<?php
class Payment extends CS_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('api', 'common'));
        $this->load->library('chinapay/chinapay', null, 'chinapay');
        $this->load->library('alipay/alipaypc', null, 'alipaypc');
        $this->load->library('ccbpay/ccbpay', null, 'ccbpay');
        $this->load->library('alidayu/alidayusms', null, 'alidayusms');
        $this->load->library('aes');
        $this->load->model('pay_record_model','pay_record');
        $this->load->model('order_base_model','order_base');
        $this->load->model('goods_base_model','goods_base');
        $this->load->model('order_profit_model','order_profit');
        $this->load->model('user_model', 'user');
        $this->load->model('user_account_model','user_account');
        $this->load->model('goods_map_cpt_model','goods_map_cpt');
        $this->load->model('order_send_model','order_send');
        $this->load->model('pay_method_model', 'pay_method');
        $this->load->model('account_log_model', 'account_log');
        $this->load->model('pay_failure_log_model', 'pay_failure_log');
        $this->load->model('order_send_model', 'order_send');
        $this->load->model('macs_model', 'macs');
        $this->load->model('tourism_goods_base_model', 'tourism_goods_base');
        $this->load->model('scenery_base_model', 'scenery_base');
        $this->load->model('ym_sms_error_model', 'ym_sms_error');
        $this->load->model('bind_user_model', 'bind_user');
    }

    /**
     * 提交订单成功
     * 付款页面
     */
    public function payOrderScenic($payId)
    {
        if (empty($payId)) {
            show_404();
        }
        $result = $this->pay_record->findByPayId($payId);
        if ($result->num_rows() <= 0) {
            show_404();
        }
        $payRecord = $result->row(0);
        $data['payRecord'] = $payRecord;

        $result1 = $this->order_base->findByPayId($payId);
        if ($result1->num_rows() <= 0) {
            show_404();
        }
        $data['orderBase'] = $result1->result();

        //测试扫码购
        if (in_array($data['orderBase'][0]->sid, array(5299, 677, 471, 3216, 1481)) && $data['orderBase'][0]->calculate_method == 3) {
            $this->redirect($this->config->wap_base_url.'wcpay/swiftpay?pay_id='.$payId);
        }

        $result3 = $this->user_account->findByUid($this->uid);
        if ($result3->num_rows() <= 0) {
            show_404();
        }
        $userAccount = $result3->row(0);
        $data['userAccount'] = $userAccount;

        $balancePay = $payRecord->amount;
        $orderBouns = $payRecord->order_bouns; //实际使用U币数量
        if ($userAccount->amount_bonus < $payRecord->order_bouns) {
            $orderBouns = $userAccount->amount_bonus >= 0 ? $userAccount->amount_bonus : 0;
        }
        $orderPay = bcsub($balancePay, $orderBouns, 2);
        $orderPay = $orderPay > 0 ? $orderPay : 0;

        $data['is_scan'] = get_cookie('scan_sid'); //是否是码购 过来的
        $data['payBank'] = $payRecord->pay_method;
        if (!in_array($payRecord->pay_method, array(99, 1, 201, 200, 210))) {
            $data['payBank'] = 99;
        }
        $data['paymethods'] = array(99=>'余额支付', 1=>'支付宝支付', 201=>'微信支付', 200=>'银联支付', 210 => '建设银行');
        $data['balance_pay'] = $orderPay;
        $data['order_bouns'] = $orderBouns;
        $this->load->view('scenic/payment/payOrderScenic', $data);
    }
    
    /**
     * 网银去支付方法。
     */
    public function orderToPay()
    {
        $payId = (int)$this->input->post('pay_id');
        $pay_bank = (int)$this->input->post('pay_bank');
        $balancePay = $this->input->post('balance_pay');
        $result = $this->pay_record->findByPayId($payId);
        if ($result->num_rows() <= 0) {
            $this->alertJumpPre('订单信息有误，或长时间未支付');
        }
        $payRecord = $result->row(0);

        if ((int)$payRecord->bit_state&65536) {
            $this->alertJumpPre('该订单已经支付，无需重新支付');
        }

        $result1 = $this->user_account->findByUid($this->uid);
        if ($result1->num_rows() <= 0) {
            $this->alertJumpPre('当前账户有误');
        }
        $userAccount = $result1->row();
        
        $orderBouns = $payRecord->order_bouns; //实际使用U币数量
        if ($userAccount->amount_bonus < $payRecord->order_bouns) {
            $orderBouns = $userAccount->amount_bonus >= 0 ? $userAccount->amount_bonus : 0;
        }
        
        $orderPay = bcsub($payRecord->amount, $orderBouns, 2);
        $orderPay = $orderPay > 0 ? $orderPay : 0;
        if ($orderPay != $balancePay) {
            $this->alertJumpPre('支付价格有误！');
        }

        $this->db->trans_begin();
        //更新支付方式
        $updatePay = $this->pay_record->updatePayRecord(array('pay_id'=>$payId, 'uid'=>$this->uid, 'order_bouns'=>$orderBouns, 'pay_method'=>$pay_bank, 'pay_time'=>time()));
        $orderUpdate = $this->order_base->updateByOrderPayId(array('pay_id'=>$payId, 'payer_uid'=>$this->uid, 'pay_method'=>$pay_bank));

        if (!$updatePay || !$orderUpdate) {
            $this->db->trans_rollback();
            $this->alertJumpPre('操作失败！');
        }
        $this->db->trans_commit();

        $orderBase = $this->order_base->findByPayId($payId);
        if ($orderBase->num_rows() == 0) {
            $this->alertJumpPre('操作失败！');
        }
        $orderBase = $orderBase->row();

          //订单交易信息
        switch ($pay_bank) {
            case '99' : //余额支付
                $this->redirect($this->config->wap_base_url.'scenic/payment/balance/'.$payId.'.html');
                break;
            case '200' : //银联支付
                $BgRetUrl = site_url('scenic/paycallback/chinapayNotify');
                $PageRetUrl = site_url('scenic/payment/chinapayReturn');
                $objPay = $this->chinapay->callChinapayApi($payId, $balancePay, 'notcart', $BgRetUrl, $PageRetUrl);
                break;
            case '201' : //微信支付
                $url = $this->config->wap_base_url.'scenic_wx_call.php?pay_id='.$payId;
                header("Location:$url");
                break;
            case '1' :    //支付宝支付
                $alipayParameter = $this->alipayParameter($payRecord, $pay_bank, $balancePay);
                $this->alipaypc->callAlipayApi($alipayParameter);
                break;
            case '210' :    //建行支付
                $parameter = array(
                    'orderId' => $payId,
                    'payment' => $balancePay,
                    'regInfo' => '', // 网站客户注册信息，中文需使用escape编码
                    'proInfo' => '', // 顾客购买的产品的信息，中文需使用escape编码
                    'remark1' => 'SCENIC' , //备注1 景区
                    'remark2' => ''
                );
                $this->ccbpay->callCcbPay($parameter);
                break;
            default :  //支付出现问题
                $this->redirect('tourism/tourism/payFail');
                break;
        }
    }
    
    /**
     * 余额支付
     */
    public function balance($pay_id)
    {
        if (!is_numeric($pay_id)) {
            show_404();
        }
        $result = $this->pay_record->findByPayId($pay_id);
        if ($result->num_rows() <= 0) {
            show_404();
        }
        $payRecord = $result->row(0);
        $data['payRecord'] = $payRecord;
        
        $result2 = $this->user_account->findByUid($this->uid);
        if ($result2->num_rows() <= 0) {
            show_404();
        }
        $userAccount = $result2->row(0);
        $data['userAccount'] = $userAccount;
        
        $balancePay = $payRecord->amount;
        $orderBouns = $payRecord->order_bouns; //实际使用U币数量
        if ($userAccount->amount_bonus < $payRecord->order_bouns) {
            $orderBouns = $userAccount->amount_bonus >= 0 ? $userAccount->amount_bonus : 0;
        }
        $orderPay = bcsub($balancePay, $orderBouns, 2);
        $orderPay = $orderPay > 0 ? $orderPay : 0;
        
        $data['balance_pay'] = $orderPay;
        $data['order_bouns'] = $orderBouns;
        $this->load->view('scenic/payment/balance', $data);
    }
    
    /**
     * 余额支付
     * 过程
     */
    public function balancePay()
    {
        $payId = (int)$this->input->post('pay_id');
        $payPw = $this->input->post('pay_pw');
        $balancePay = $this->input->post('balance_pay');
        $result = $this->pay_record->findByPayId($payId);
        if ($result->num_rows() <= 0) {
            $this->jsonMessage('订单信息有误，或长时间未支付');
        }
        $payRecord = $result->row(0);
    
        if ((int)$payRecord->bit_state&65536) {
            $this->jsonMessage('该订单已经支付，无需重新支付');
        }
    
        $result1 = $this->user->validatePayPw($this->uid, $payPw);
        if ($result1->num_rows() <= 0) {
            $this->jsonMessage('密码填写错误，请重新输入');
        }
        $user = $result1->row(0);
    
        $result3 = $this->user_account->findByUid($this->uid);
        if ($result3->num_rows() <= 0) {
            $this->jsonMessage('当前账户有误');
        }
        $userAccount = $result3->row(0);
    
        $orderBouns = $payRecord->order_bouns; //实际使用U币数量
        if ($userAccount->amount_bonus < $payRecord->order_bouns) {
            $orderBouns = $userAccount->amount_bonus >= 0 ? $userAccount->amount_bonus : 0;
        }
    
        $orderPay = bcsub($payRecord->amount, $orderBouns, 2);
        $orderPay = $orderPay > 0 ? $orderPay : 0;
        if ($orderPay != $balancePay) {
            $this->jsonMessage('支付价格有误！');
        }
    
        if ($userAccount->amount_carry < $balancePay) {
            $this->jsonMessage('余额不足，您可以选择其它支付方式');
        }
    
        $result4 = $this->order_base->findByPayId($payId);
        if ($result4->num_rows() <= 0) {
            $this->jsonMessage('订单信息有误，或长时间未支付哦');
        }
        $orderBase = $result4->result();
    
        $this->db->trans_begin();
        //修改pay_record表的支付记录
        $updatePay = $this->pay_record->updatePayRecord(array('pay_id'=>$payId, 'uid'=>$this->uid, 'order_bouns'=>$orderBouns, 'pay_method'=>99, 'bit_state'=>65536, 'pay_time'=>time()));
        $orderUpdate = $this->order_base->updateByOrderPayId(array('pay_id'=>$payId, 'payer_uid'=>$this->uid, 'bit_pay'=>65536, 'pay_method'=>99, 'paytime'=>time()));
    
        $payProfit = array(); //如果是支付后分润，则执行分润操作
        $accountLog = array();
        foreach ($orderBase as $key=>$order) {
            if ((int)$order->bit_opt&4) { //需要支付后分润的订单
                $payProfit[$order->order_id] = $order;
            }
            $accountLog[$key]['order_id']     = $order->order_id;
            $accountLog[$key]['uid']          = $order->payer_uid;
            $accountLog[$key]['amount']       = $order->amount_fee;
            $accountLog[$key]['date']         = date('Y-m-d H:i:s');
            $accountLog[$key]['type']         = PAY;
            $accountLog[$key]['account_type'] = ACCOUNT_TYPE_CARRY;
            $accountLog[$key]['product_type'] = 'scenic';
    
            //支付后减去库存，更新已售数量
            $update = $this->goods_base->setTicketStock(array('goods_id'=>$order->goods_id, 'sold_number'=>$order->goods_num, 'limit_number'=>-$order->goods_num));
        }
        if (!empty($payProfit)) {
            $error = $this->orderExecuteProfit($payProfit);
            if (!empty($error)) {
                $this->db->trans_rollback();
                $this->jsonMessage($error);
            }
        }
        //扣除余额支付的金额
        $updateAccount = $this->user_account->updateUserAccount($this->uid, array('amount_carry'=>-$balancePay, 'amount_bonus'=>-$orderBouns));
        $inserAccountLog = $this->account_log->insertBatch($accountLog);
    
        if (!$updatePay || !$orderUpdate || !$updateAccount || !$inserAccountLog) {
            $this->db->trans_rollback();
            $this->jsonMessage('支付失败！');
        }
    
        $this->sendOrderBaseMessage($orderBase, $user); //给订单发送短信
    
        $this->db->trans_commit();
        
        //推送支付延迟 的订单到机器
        $this->sendOrderToMac($payRecord, $orderBase[0]->sid);

        //获得接口对接产品,进行对接
        $this->autoDockingApi($payRecord);

        $this->jsonMessage('', site_url('scenic/payment/paySuccess/'.$payId));
    }
    
    /**
     * 获取支付宝需要参数。
     * @param object $payRecord
     * @param paybank $pay_bank
     * @param object $balancePay --- 订单支付总金额
     * @return array
     */
    private function alipayParameter($payRecord, $pay_bank, $balancePay)
    {
        $parameter = array(
            'out_trade_no' => $payRecord->pay_id,
            'subject'      => $payRecord->pay_id,
            'total_fee'    => $balancePay,
            'body'         => $payRecord->body,
            'show_url'     => $_SERVER['HTTP_REFERER'],
            'notify_url'   => site_url('scenic/paycallback/alipayNotify'),
            'call_back_url'=> site_url('scenic/payment/alipayReturn'),
            'pay_method'   => $pay_bank
        );
        $payBankCode = $this->pay_method->findByBankId($pay_bank);
        $parameter['defaultbank'] = $payBankCode->bank_code;
        return $parameter;
    }
    
    /**
     * 支付宝支付
     * 同步回调函数。 ok
     */
    public function alipayReturn()
    {
        $response = $this->alipaypc->responseAlipayReturn();
        $payId = $this->input->get('out_trade_no');
        $result = $this->pay_record->findByPayId($payId);
        if ($result->num_rows() <= 0) {
            $this->payError('订单信息有误，或长时间未支付');
            return ;
        }
        $payRecord = $result->row(0);
        
        if ($response) { //$response付款成功；
            if ((int)$payRecord->bit_state&65536) { //如果支付过
                $this->redirect($this->config->wap_base_url. 'scenic/payment/paySuccess/'.$payRecord->pay_id.'.html');
            }
            
            $result2 = $this->order_base->findByPayId($payId);
            if ($result2->num_rows() <= 0) {
                $this->payError('订单信息有误，或长时间未支付', $payId);
                return ;
            }
            $orderBase = $result2->result();
            
            $this->db->trans_begin();
            //更新支付状态
            $updatePay = $this->pay_record->updatePayRecord(array('pay_id'=>$payId, 'bit_state'=>65536, 'pay_time'=>time()));
            $orderUpdate = $this->order_base->updateByOrderPayId(array('pay_id'=>$payId, 'bit_pay'=>65536, 'paytime'=>time()));

            //扣除金币支付的金额
            if ($payRecord->order_bouns > 0) {
                $updateAccount = $this->user_account->updateUserAccount($payRecord->uid, array('amount_bonus'=>-$payRecord->order_bouns));
                if (!$updateAccount) {
                    $this->db->trans_rollback();
                    $this->payError('扣除金币失败！', $payId);
                    return ;
                }
            }
            
            $payProfit = array(); //如果是支付后分润，则执行分润操作
            foreach ($orderBase as $key=>$order) {
                if ((int)$order->bit_opt&4) { //需要支付后分润的订单
                    $payProfit[$order->order_id] = $order;
                }
                //支付后减去库存，更新已售数量
                $update = $this->goods_base->setTicketStock(array('goods_id'=>$order->goods_id, 'sold_number'=>$order->goods_num, 'limit_number'=>-$order->goods_num));
            }
            if (!empty($payProfit)) {
                $error = $this->orderExecuteProfit($payProfit);
                if (!empty($error)) {
                    $this->db->trans_rollback();
                    $this->jsonMessage($error);
                }
            }
            
            if (!$updatePay || !$orderUpdate) {
                $this->db->trans_rollback();
                $this->payError('操作失败！', $payId);
                return ;
            }
            
            $this->sendOrderBaseMessage($orderBase); //给订单发送短信
            
            $this->db->trans_commit();
            
            //推送支付延迟 的订单到机器
            $this->sendOrderToMac($payRecord, $orderBase[0]->sid);
            
            //获得接口对接产品,进行对接
            $this->autoDockingApi($payRecord);
            
            $this->redirect($this->config->wap_base_url. 'scenic/payment/paySuccess/'.$payRecord->pay_id.'.html');
        } else {
            $result = $this->pay_failure_log->findByOrderSn($payId);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($payId, $this->input->get(), array('status'=>$response));
            }
            $this->payError($response, $payId);
        }
    }
    
    /**
     * 银联支付
     * 同步回调函数，主订单pay_id
     */
    public function chinapayReturn()
    {
        $postData = $this->input->post();
        $response = $this->chinapay->responseChinapayApi($postData);
        $payId = $this->input->post('orderno');
        $result = $this->pay_record->findByPayId($payId);
        if ($result->num_rows() <= 0) {
            $this->payError('订单信息有误，或长时间未支付');
            return ;
        }
        $payRecord = $result->row(0);
    
        if ($response === true) { //$response付款成功；
            if ((int)$payRecord->bit_state&65536) { //如果支付过
                $this->redirect($this->config->wap_base_url. 'scenic/payment/paySuccess/'.$payRecord->pay_id.'.html');
            }
    
            $result2 = $this->order_base->findByPayId($payId);
            if ($result2->num_rows() <= 0) {
                $this->payError('订单信息有误，或长时间未支付', $payId);
                return ;
            }
            $orderBase = $result2->result();
    
            $this->db->trans_begin();
            //更新支付状态
            $updatePay = $this->pay_record->updatePayRecord(array('pay_id'=>$payId, 'bit_state'=>65536, 'pay_time'=>time()));
            $orderUpdate = $this->order_base->updateByOrderPayId(array('pay_id'=>$payId, 'bit_pay'=>65536, 'paytime'=>time()));
            
            //扣除金币支付的金额
            if ($payRecord->order_bouns > 0) {
                $updateAccount = $this->user_account->updateUserAccount($payRecord->uid, array('amount_bonus'=>-$payRecord->order_bouns));
                if (!$updateAccount) {
                    $this->db->trans_rollback();
                    $this->payError('扣除金币失败！', $payId);
                    return ;
                }
            }
            
            $payProfit = array(); //如果是支付后分润，则执行分润操作
            foreach ($orderBase as $key=>$order) {
                if ((int)$order->bit_opt&4) { //需要支付后分润的订单
                    $payProfit[$order->order_id] = $order;
                }
                //支付后减去库存，更新已售数量
                $update = $this->goods_base->setTicketStock(array('goods_id'=>$order->goods_id, 'sold_number'=>$order->goods_num, 'limit_number'=>-$order->goods_num));
            }
            if (!empty($payProfit)) {
                $error = $this->orderExecuteProfit($payProfit);
                if (!empty($error)) {
                    $this->db->trans_rollback();
                    $this->jsonMessage($error);
                }
            }
    
            if (!$updatePay || !$orderUpdate) {
                $this->db->trans_rollback();
                $this->payError('操作失败！', $payId);
                return ;
            }
    
            $this->sendOrderBaseMessage($orderBase); //给订单发送短信
            
            $this->db->trans_commit();
            
            //推送支付延迟 的订单到机器
            $this->sendOrderToMac($payRecord, $orderBase[0]->sid);
            
            //获得接口对接产品,进行对接
            $this->autoDockingApi($payRecord);
            
            $this->redirect($this->config->wap_base_url. 'scenic/payment/paySuccess/'.$payRecord->pay_id.'.html');
        } else {
            $result = $this->pay_failure_log->findByOrderSn($payId);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($payId, $postData, array('status'=>$response));
            }
            $this->payError($response, $payId);
        }
    }

    /**
     * 建行支付
     * 同步回调函数，主订单pay_id
     */
    public function ccbpayReturn()
    {
        $postData = $this->input->get();
        $response = $this->ccbpay->responseCcbReturn();
        $payId = $this->input->get('ORDERID', true);
        $result = $this->pay_record->findByPayId($payId);
        if ($result->num_rows() <= 0) {
            $this->payError('订单信息有误，或长时间未支付');
            return ;
        }
        $payRecord = $result->row(0);
        if ($response === TRUE) { //$response付款成功；
            if ((int)$payRecord->bit_state&65536) { //如果支付过
                $this->redirect($this->config->wap_base_url. 'scenic/payment/paySuccess/'.$payRecord->pay_id.'.html');
            }

            $result2 = $this->order_base->findByPayId($payId);
            if ($result2->num_rows() <= 0) {
                $this->payError('订单信息有误，或长时间未支付', $payId);
                return ;
            }
            $orderBase = $result2->result();

            $this->db->trans_begin();
            //更新支付状态
            $updatePay = $this->pay_record->updatePayRecord(array('pay_id'=>$payId, 'bit_state'=>65536, 'pay_time'=>time()));
            $orderUpdate = $this->order_base->updateByOrderPayId(array('pay_id'=>$payId, 'bit_pay'=>65536, 'paytime'=>time()));
            
            //扣除金币支付的金额
            if ($payRecord->order_bouns > 0) {
                $updateAccount = $this->user_account->updateUserAccount($payRecord->uid, array('amount_bonus'=>-$payRecord->order_bouns));
                if (!$updateAccount) {
                    $this->db->trans_rollback();
                    $this->payError('扣除金币失败！', $payId);
                    return ;
                }
            }
            
            $payProfit = array(); //如果是支付后分润，则执行分润操作
            foreach ($orderBase as $key=>$order) {
                if ((int)$order->bit_opt&4) { //需要支付后分润的订单
                    $payProfit[$order->order_id] = $order;
                }
                //支付后减去库存，更新已售数量
                $update = $this->goods_base->setTicketStock(array('goods_id'=>$order->goods_id, 'sold_number'=>$order->goods_num, 'limit_number'=>-$order->goods_num));
            }
            if (!empty($payProfit)) {
                $error = $this->orderExecuteProfit($payProfit);
                if (!empty($error)) {
                    $this->db->trans_rollback();
                    $this->jsonMessage($error);
                }
            }
    
            if (!$updatePay || !$orderUpdate) {
                $this->db->trans_rollback();
                $this->payError('操作失败！', $payId);
                return ;
            }
    
            $this->sendOrderBaseMessage($orderBase); //给订单发送短信
            
            $this->db->trans_commit();
            
            //推送支付延迟 的订单到机器
            $this->sendOrderToMac($payRecord, $orderBase[0]->sid);
            
            //获得接口对接产品,进行对接
            $this->autoDockingApi($payRecord);
            
            $this->redirect($this->config->wap_base_url. 'scenic/payment/paySuccess/'.$payRecord->pay_id.'.html');
        } else {
            $result = $this->pay_failure_log->findByOrderSn($payId);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($payId, $postData, array('status'=>$this->ccbpay->getMessage()));
            }
            $this->payError($response, $payId);
        }
    }
    
    /*微信支付成功回调*/
    public function wxSuccessCompletePay($payId)
    {
        $err_msg = $this->input->get('err_msg');
        if ($err_msg && $err_msg == 'get_brand_wcpay_request:ok') {
            $result = $this->pay_record->findByPayId($payId);
            if ($result->num_rows() <= 0) {
                $this->payError('订单信息有误，或长时间未支付');
                return ;
            }
            $payRecord = $result->row(0);
            if ((int)$payRecord->bit_state&65536) { //如果支付过
                $this->redirect($this->config->wap_base_url. 'scenic/payment/paySuccess/'.$payRecord->pay_id.'.html');
            }  else {
                $this->redirect($this->config->wap_base_url. 'scenic/payment/wxFailCompletePay/'.$payId.'.html');
            }
            $this->redirect($this->config->wap_base_url. 'scenic/payment/paySuccess/'.$payRecord->pay_id.'.html');
        } else {
            $this->redirect($this->config->wap_base_url. 'scenic/payment/wxFailCompletePay/'.$payId.'.html');
        }
    }
    
    /*微信支付失败*/
    public function wxFailCompletePay($payId)
    {

        $orderInfo = $this->pay_record->findByPayId($payId);
        if ($orderInfo->num_rows() <= 0) {
            $this->payError('此订单不合法，或者不存在');
            return ;
        }

        $payRecord = $orderInfo->row(0);
        
        $result = $this->pay_failure_log->findByOrderSn($payId);
        if (!$result) { //保存错误日志。
            $last_id = $this->pay_failure_log->insertPayFailureLog($payId, $this->input->get(), array('status'=>false));
        }

        $this->payError('微信支付出错', $payId);
    }

    /**
     * 兴业银行(威富通) 支付
     * 支付宝回调
     * 同步回调函数，主订单pay_id
     */
    public function swiftReturn()
    {
        $postData = $this->input->get();
        $payId = $this->input->get('pay_id', true);
        $sign = $this->input->get('sign', true);
        $result = $this->pay_record->findByPayId($payId);
        if ($result->num_rows() <= 0) {
            $this->payError('订单信息有误，或长时间未支付', $payId);
            return ;
        }
        $payRecord = $result->row(0);
        if ($this->createSign($payRecord) == $sign) { //$response付款成功；
            if ((int)$payRecord->bit_state&65536) { //如果支付过
                $this->redirect($this->config->wap_base_url. 'scenic/payment/paySuccess/'.$payRecord->pay_id.'.html');
            }

            $result2 = $this->order_base->findByPayId($payId);
            if ($result2->num_rows() <= 0) {
                $this->payError('订单信息有误，或长时间未支付', $payId);
                return ;
            }
            $orderBase = $result2->result();

            $this->db->trans_begin();
            //更新支付状态
            $updatePay = $this->pay_record->updatePayRecord(array('pay_id'=>$payId, 'bit_state'=>65536, 'pay_method' => 188,'serial_number' => $response['transaction_id'], 'pay_time'=>time()));
            $orderUpdate = $this->order_base->updateByOrderPayId(array('pay_id'=>$payId, 'bit_pay'=>65536, 'pay_method' => 188, 'paytime'=>time()));
            
            //扣除金币支付的金额
            if ($payRecord->order_bouns > 0) {
                $updateAccount = $this->user_account->updateUserAccount($payRecord->uid, array('amount_bonus'=>-$payRecord->order_bouns));
                if (!$updateAccount) {
                    $this->db->trans_rollback();
                    $this->payError('扣除金币失败！', $payId);
                    return ;
                }
            }
            
            $payProfit = array(); //如果是支付后分润，则执行分润操作
            foreach ($orderBase as $key=>$order) {
                if ((int)$order->bit_opt&4) { //需要支付后分润的订单
                    $payProfit[$order->order_id] = $order;
                }
                //支付后减去库存，更新已售数量
                $update = $this->goods_base->setTicketStock(array('goods_id'=>$order->goods_id, 'sold_number'=>$order->goods_num, 'limit_number'=>-$order->goods_num));
            }
            if (!empty($payProfit)) {
                $error = $this->orderExecuteProfit($payProfit);
                if (!empty($error)) {
                    $this->db->trans_rollback();
                    $this->jsonMessage($error);
                }
            }
    
            if (!$updatePay || !$orderUpdate) {
                $this->db->trans_rollback();
                $this->payError('操作失败！', $payId);
                return ;
            }
    
            $this->sendOrderBaseMessage($orderBase); //给订单发送短信
            
            $this->db->trans_commit();
            
            //推送支付延迟 的订单到机器
            $this->sendOrderToMac($payRecord, $orderBase[0]->sid);
            
            //获得接口对接产品,进行对接
            $this->autoDockingApi($payRecord);
            
            $this->redirect($this->config->wap_base_url. 'scenic/payment/paySuccess/'.$payRecord->pay_id.'.html');
        } else {
            $result = $this->pay_failure_log->findByOrderSn($payId);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($payId, $postData, '');
            }
            $this->payError('支付失败', $payId);
        }
    }

    /**
     * 签名
     */
    private function createSign($payRecord)
    {
        $parameters = array(
            'pay_id'     => $payRecord->pay_id,
            'level'      => $payRecord->level,
            'cat_ids'    => $payRecord->cat_ids,
            'goods_ids'  => $payRecord->goods_ids,
            'goods_nums' => $payRecord->goods_nums,
            'order_ids'  => $payRecord->order_ids,
            'uid'        => $payRecord->uid,
            'amount'     => $payRecord->amount
        );

        $signPars = "";
        ksort($parameters);
        foreach($parameters as $k => $v) {
            if("" != $v && "sign" != $k) {
                $signPars .= $k . "=" . $v . "&";
            }
        }
        $signPars = rtrim($signPars, '&');

        return strtolower(md5($signPars));
    }
    
    /**
     * 如果无支付后分润或执行无误
     * 则返回空，否则返回错误信息
     * @param unknown $orderBase
     * @return string
     */
    private function orderExecuteProfit($orderBase)
    {
        //执行分润操作
        return '';
    }
    
    /**
     * 支付成功页面
     */
    public function paySuccess($pay_id)
    {
        if (!is_numeric($pay_id)) {
            show_404();
        }
        $result = $this->order_base->findByPayId($pay_id);
        if ($result->num_rows() <= 0) {
            show_404();
        }
        $result = $result->row();
        $scenicBase = $this->scenery_base->findBySid($result->sid);
        if ($scenicBase->num_rows() <= 0) {
            show_404();
        }
        $data['scenicInfo'] = $scenicBase->row(0);
        $data['orderInfo'] = $result;
        $this->load->view('scenic/payment/paySuccess', $data);
    }

    /**
     * 支付失败页面
     */
    public function payError($message='您的网络不稳定', $payId = 0)
    {
        $data = array();
        if (is_array($message)) {
            $data['message'] = implode(',', $message);
        } else {
            switch ($message) {
                case 'wx':
                    $data['message'] = '微信支付失败';
                    break;
                case 'ali':
                    $data['message'] = '支付宝支付失败';
                    break;
                default:
                    $data['message'] = $message;
                    break;
            }
            
        }

        if ($payId && is_numeric($payId)) {
            $result = $this->order_base->findByPayId($payId);
            if ($result->num_rows() <= 0) {
                show_404();
            }
            $result = $result->row();
            $scenicBase = $this->scenery_base->findBySid($result->sid);
            if ($scenicBase->num_rows() <= 0) {
                show_404();
            }
            $data['scenicInfo'] = $scenicBase->row(0);
            $data['orderInfo'] = $result;
        }
        $this->load->view('scenic/payment/payError', $data);
    }

    /**
     * 给景区订单发送短信
     * @param unknown $orderBase
     */
    private function sendOrderBaseMessage($orderBase, $user)
    {
        foreach ($orderBase as $k=>$item) {
            //如果是深大(智游宝)接口、九天科技(票付通)接口、皇家海洋馆接口、哈尔滨极地馆接口、银科环企(大汖温泉、梦幻海、热高)接口、联动票务接口、深大(智游宝)新接口、千朝农谷接口、畅游通(武当山、云丘山、善卷洞、圣井山、哈尔滨极地馆)接口、驴妈妈接口、青海湖接口、票付通（九天科技）新接口、天时同城接口时，着想不发短信
            if (!in_array($item->api_id, array(1, 4, 5, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24))) {
                $smsParam = array();
                $period = ' 出游日期：'.date('Y-m-d', $item->plantime);
                if (empty($item->start_time) && empty($item->end_time)) {
                    $startTime = $item->start_time ? $item->start_time : date('Y-m-d');
                    $endTime = $item->end_time ? $item->end_time : date('Y-12-31');
                    $period = ' 有效期'.$startTime.'至'.$endTime;
                }
                $smsParam['msg'] = $item->provider_name.'-'.$item->goods_name.$item->goods_num;

                if ($item->calculate_method == 3) {
                    $smsParam['order'] = $item->order_id.'），'.$period;
                    $smsParam['payId'] = $item->pay_id;
                    $smsTemplateCode = 'SMS_53550036';
                    //$message = '您已成功预订了'.$item->provider_name.'-'.$item->goods_name.$item->goods_num.'张（订单号：'.$item->order_id.'），'.$period.'，凭订票身份证或订单二维码入园。点击http://wap.zxkj918.com/scenic/order/index 查看订单二维码,如有疑问详询400-0571-648，登录http://wap.zxkj918.com下载APP了解更多产品。';
                } else {
                    if (strlen($item->sfz)<15) { //短信验证码
                        $smsParam['order'] = $item->order_id;
                        $smsParam['code'] = $item->sfz;
                        $smsTemplateCode = 'SMS_37135040';
                        //$message = '您已成功预订了'.$item->provider_name.'-'.$item->goods_name.$item->goods_num.'张（订单号：'.$item->order_id.'），验证码:'.$item->sfz.$period.'，如有疑问请致电400-0571-648。';
                    } else {
                        $smsParam['order'] = $item->order_id.'），'.$period;
                        $smsTemplateCode = 'SMS_37125088';
                        //$message = '您已成功预订了'.$item->provider_name.'-'.$item->goods_name.$item->goods_num.'张（订单号：'.$item->order_id.'），'.$period.'，凭订票身份证入园。如需换票或选择到景区支付,可在景区指定地点换票，如有疑问请致电400-0571-648。';
                    }
                }
                if ($user->sms == 1) { //表示短信带后缀名称
                    $smsParam['payer_name'] = '400-0571-648。-'.$item->payer_name;
                    //$message = $message.'-'.$item->payer_name;
                } else {
                    $smsParam['payer_name'] = '400-0571-648。';
                }
                //$this->sendToSms($item->phone, $message, 2);
                $alidayusms = $this->alidayusms->smsNumSend($item->phone, json_encode($smsParam), $smsTemplateCode);
                if (isset($alidayusms['success']) && $alidayusms['success'] == 'false') {
                    $this->ym_sms_error->insertYmSmsError($item->phone, json_encode($smsParam), json_encode($alidayusms), 4);
                }
            }
        }
    }
    
    /**
     * 对接接口
     * @param unknown $payRecord
     */
    private function autoDockingApi($payRecord)
    {
        //初始化o_api_id_ary和o_goods_id_ary
        $o_api_id_ary = array();
        $o_goods_id_ary = array();
        
        //获得产品id
        $goodsIdsAry = unserialize($payRecord->goods_ids);
        //获得订单id
        $orderIdsAry = unserialize($payRecord->order_ids);
        //根据产品id查询接口对接信息
        $goodsBaseWhere = array('goods_ids'=>$goodsIdsAry);
        $goodsBaseQuery = $this->goods_base->findByParams($goodsBaseWhere);
        $goodsBaseResult = $goodsBaseQuery->result();
        foreach ($goodsBaseResult as $key => $goodsBaseRow) {
            $o_api_id = $goodsBaseRow->o_api_id;
            $o_goods_id = $goodsBaseRow->o_goods_id;
            
            if (!empty($o_api_id) && !empty($o_goods_id)) {
                array_push($o_api_id_ary, $o_api_id);//给$o_api_id_ary赋值
                array_push($o_goods_id_ary, $o_goods_id);//给$o_goods_id_ary赋值
            }
        }
        
        //如果有$o_api_id_ary、$o_goods_id_ary和$orderIdsAry,就自动对接
        if ($o_api_id_ary && $o_goods_id_ary && $orderIdsAry) {
            $params = array(
                'o_type'         => 1,//表示下单
                'o_api_id_ary'   =>$o_api_id_ary,
                'o_goods_id_ary' => $o_goods_id_ary,
                'order_id_ary'   => $orderIdsAry,
            );
            $curlPost = 'params='.json_encode($params);
            
            //$url = $this->config->www_base_url.'api/api';//对外接口地址(用于接他网接口)
            $url = $this->config->api_base_url.'api';//对外接口地址(用于接他网接口)
            getApiDynamic($curlPost, $url);
        }
    }
    
    /**
     * 处理景区订单机器漏单：
     * 1，A用户订单先买票，但没有支付
     * 2，然后B用户购买，完成支付
     * 3，A用户支付完成
     * 处理办法：
     * 在付款完成后，加入判断： 查询该景区订单最大一个订单，
     * 如果现在现在支付的订单小于最大订单，就在订单推送表（order_send）加一条
     * 如果大于不用操作
     **/
    private function sendOrderToMac($payRecord, $sid)
    {
        if ($sid) {
            $result = $this->order_base->findMaxOrderId($payRecord->pay_id, $sid);
            if ($result->num_rows() > 0) {
                $macs = $this->macs->findBySid($sid);
                if ($macs->num_rows() > 0) {
                    $orderIds = unserialize($payRecord->order_ids);
                    if ( ! empty($orderIds) && is_array($orderIds)) {
                        $this->order_send->addBatch($orderIds, $macs->result());
                    }
                }
            }
        }
        
        //微信购买成功提醒
        $openUser = $this->purchaseSuccess($payRecord);
    }
    
    /**
     * 微信授权
     */
    public function purchaseSuccess($payRecord)
    {
        $result = $this->bind_user->findByOpenOrAli($payRecord->uid);
        if ($result->num_rows() <= 0) {
            return false;
        }
        $bindUser = $result->row(0);
        $openId = $bindUser->open_id;
        include_once(APPPATH.'libraries/wxpay/WxPayPubHelper/WxPayPubHelper.php');
        $jsapi = new JsApi_pub();
        $accessToken = $jsapi->getAccessToken();
        if (isset($accessToken->errcode)) {
            return $accessToken->errmsg;
        }
        $urlOne = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$accessToken->access_token;
        $data['touser']           = $openId;
        $data['template_id']      = 'zFSPosWPThOgUiZcu7ywOBfHgikG6n-Sj1slBhyVQqw';
        $data['url']              = $this->config->wap_base_url.'scenic/order/index.html';
        $data['data']['first']    = array('value' => '恭喜您，付款成功了','color' => '#173177');;
        $data['data']['keyword1'] = array('value' => $payRecord->body,'color' => '#173177');
        $data['data']['keyword2'] = array('value' => $payRecord->pay_id,'color' => '#173177');
        $data['data']['keyword3'] = array('value' => $payRecord->amount,'color' => '#173177');
        $data['data']['keyword4'] = array('value' => date('Y-m-d H:i'),'color' => '#173177');
        $data['data']['remark']   = array('value' => '感谢您的光临，欢迎再次购买！','color' => '#173177');
        $res = json_decode(getApiDynamic(json_encode($data), $urlOne));
        if ($res->errcode != 0) {
            return false;
        }
        return TRUE;
    }
}
